package com.gxa.autoparts.portal.interceptor;
import com.alibaba.fastjson.JSON;
import com.gxa.autoparts.core.common.ExceptionCode;
import com.gxa.autoparts.core.common.JsonResult;
import com.gxa.autoparts.core.exception.BusinessException;
import com.gxa.autoparts.core.pojo.User;
import com.gxa.autoparts.core.util.RestUtil;
import com.gxa.autoparts.core.util.ThreadLocalUtil;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.util.Map;

/**
 * @author HS
 */

public class PermissionInterceptor implements HandlerInterceptor {

    /**
     * 在方法执行前执行的操作
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
//        String token = request.getHeader("token");
//        if(token==null){
//            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
//        }
//        //指定uri地址
//        String uri="http://localhost:8090/sso/findUserByToken";
//        // 参数, 用Spring封装的MultiValueMap
//        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
//        paramMap.add("token", token);
//        //调用postForObject方法, 指定uri/参数/返回值类型
//        // 返回值如果是一个json字符串, 就可以用JsonUtil来解析
//        JsonResult jsonResult = RestUtil.postWithParams(uri, paramMap);
//        String code = jsonResult.getCode();
//        if(code.equals("200")){
//            Object data = jsonResult.getData();
//            String jsonString = JSON.toJSONString(data);
//            User user = JSON.parseObject(jsonString,User.class);
//            ThreadLocalUtil.set(user.getId());
//            return true;
//        }else {
//
//            throw new BusinessException(ExceptionCode.TOKEN_INVALID);
//        }
        //把json字符串转换为User对象

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在方法执行后执行的操作(指放行后)
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
